package com.topcent.tioxyc.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.topcent.tioxyc.constants.KeyConstant;
import com.topcent.tioxyc.pojo.*;
import com.topcent.tioxyc.pojo.vo.Lin;
import com.topcent.tioxyc.util.ApiClient;
import com.topcent.tioxyc.util.ConnmeUtils;
import com.topcent.tioxyc.util.PurchaseCommunity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.Header;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: 陈百万
 * @date: 2025/5/15 10:34
 * @Description: 入库凭证-陈百万改造最新逻辑
 */
@Slf4j
@RestController
public class RuKuDanNewController {
    @Autowired
    private static final String DATA_CREATE = "data_create";
    private static final String DATA_UPDATE = "data_update";

    private static final String SECRET = "m0xLhBCTpqNe9SDSlNMv7Hdk";

    @PostMapping("/RuKuDanNew")
    public String ruKuDanNew(@RequestParam("nonce") String nonce,
                           @RequestParam("timestamp") String timestamp,
                           @RequestHeader("x-jdy-signature") String signature,
                           @RequestBody String payload) {
        if (!validateSignature(nonce, payload, timestamp, signature)) {
            return "fail";
        }
        // 在这里处理消息
        handleData(payload);

        return "success";
    }

    private void handleData(String payload) {
        // 在这里处理推送来的数据
        JSONObject payloadJSON = JSONUtil.parseObj(payload);
        String op = payloadJSON.getStr("op");
        String data = payloadJSON.getStr("data");

        if (DATA_CREATE.equals(op)) {
            changeManey(data);
        }
    }

    // 查询拷贝数据表的数据，处理入库凭证最新创建金额。
    private void changeManey(String data) {
        Header[] headers = ConnmeUtils.createHeaders();
        InvoiceDocument invoiceDocument = JSONUtil.toBean(data, InvoiceDocument.class);
        // 定义变量用于存储分摊金额总和和未付金额总和
        BigDecimal totalAllocationAmount = BigDecimal.ZERO;  // 已付总金额
        BigDecimal totalUnpaidAmount = BigDecimal.ZERO;  // 未付总金额
        //BigDecimal totalBalanceAmount = BigDecimal.ZERO;   // 尾款未付总金额

        for (InvoiceDocument.InvoiceLineItem invoiceLineItem : invoiceDocument.get_widget_1727340673732()) {
            HashMap<String, String> communti = new HashMap<>();
            //把其他采购订单的付款金额拿过来。
            Map<String, Object> cgdd = new HashMap<>();
            cgdd.put("app_id", "6690c7633df0f4b90b4ef551");
            //采购订单_拷贝数据（陈志生）669df675b02f2a74e35ca2f9
            cgdd.put("entry_id", "669df675b02f2a74e35ca2f9");

            communti.put("_widget_1721628277543", invoiceLineItem.get_widget_1727340673739());
            communti.put("_widget_1721628277558", invoiceLineItem.get_widget_1727340673735());
            List<SAPPurchaseOrder> sapPurchaseOrders = PurchaseCommunity.queryBased(cgdd, headers, communti, SAPPurchaseOrder.class);
            // 含税金额不能为空
            if (sapPurchaseOrders.isEmpty() || sapPurchaseOrders.getFirst() == null ||
                    sapPurchaseOrders.getFirst().get_widget_1724225500094() == null) {
                continue;
            }

            // 如果采购订单查询结果不为空，取出已付金额
            BigDecimal paidAmount = sapPurchaseOrders.getFirst().get_widget_1722475785243() == null
                    ? BigDecimal.ZERO
                    : BigDecimal.valueOf(sapPurchaseOrders.getFirst().get_widget_1722475785243());

            // 明细表.已付金额
            invoiceLineItem.set_widget_1731575068806(paidAmount);

            // 计算未付金额 unpaidAmount
            BigDecimal zongshu = invoiceLineItem.get_widget_1727340673745();

            BigDecimal unpaidAmount = zongshu
                    .subtract(paidAmount)
                    .setScale(10, RoundingMode.HALF_UP);

            // 明细表.未付金额
            invoiceLineItem.set_widget_1731575068807(unpaidAmount);

            // 累加到分摊金额总和和未付金额总和
            totalAllocationAmount = totalAllocationAmount.add(paidAmount);
            totalUnpaidAmount = totalUnpaidAmount.add(unpaidAmount);
        }
        invoiceDocument.set_widget_1731638214169(totalAllocationAmount);
        invoiceDocument.set_widget_1731638214170(totalUnpaidAmount);
        invoiceDocument.set_widget_1731915520417(totalUnpaidAmount);

        Map<String, Object> parameterInster = new HashMap<>();
        parameterInster.put("app_id", "66a0c3efcd4dd2a1c8a4a13f");
        // 入库凭证：66a3727ee9d0a8542c969091
        parameterInster.put("entry_id", "66a3727ee9d0a8542c969091");
        parameterInster.put("is_start_trigger", "true");
        parameterInster.put("data_id", invoiceDocument.get_id());
        invoiceDocument.set_id(null);
        parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(invoiceDocument));
        String jsonSalee = JSONUtil.toJsonStr(parameterInster);
        ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalee);
    }

    private boolean validateSignature(String nonce, String payload, String timestamp, String signature) {
        String calculatedSignature = getSignature(nonce, payload, timestamp);
        return calculatedSignature.equals(signature);
    }

    private String getSignature(String nonce, String payload, String timestamp) {
        return DigestUtils.sha1Hex(nonce + ":" + payload + ":" + RuKuDanNewController.SECRET + ":" + timestamp);
    }
}
